import * as THREE from 'three';
import Stat from 'three/examples/jsm/libs/stats.module'
import { CSS2DObject, CSS2DRenderer } from '../assert/js/CSS2DRenderer'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import ColladaLoader from '../assert/js/ColladaLoader'


const debug = true
const scene = new THREE.Scene();
/**
 * 创建网格模型
 */
// 辅助坐标系 
if (debug) {
    var axes = new THREE.AxesHelper(1000);
    scene.add(axes);
}

const loader = new ColladaLoader();

let qs = {}
;(() => {
    const query = window.location.search.substring(1);
    let res = {}
    const vars = query.split("&");
    for (let i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        res[pair[0]] = pair[1]
    }
    qs = res
})()


let groupArr, colorJson
let dy, dx, stat

let loadUrl
if(debug){
    loadUrl = `../assert/dae/${qs.dae.trim()}.dae`
}else{
    loadUrl = `https://xiaoji-hangzhou.oss-cn-hangzhou.aliyuncs.com/dae/${qs.dae.trim()}.dae`
}
// 添加模型
loader.load(loadUrl, result => {
    let mesh = result.scene
    let box = new THREE.Box3().setFromObject(mesh);  // 定位  
    mesh.rotation.x = - 0 / 180 * Math.PI //x轴对齐
    mesh.rotation.y = - 0 / 180 * Math.PI
    mesh.rotation.z = 90 / 180 * Math.PI
    let mdwid = box.max.x - box.min.x;
    let mdHei = box.max.z - box.min.z;
    dy = mdwid / 2 + box.min.x
    dx = mdHei / 2 + box.min.z

    mesh.position.set(-this.dx, -this.dy)


    groupArr = result.scene.children[0].children

    // if(colorUrl){
    //     fetch(colorUrl).then(async res => {
    //         colorJson = await res.json()


    //     })
    // }
    scene.add(mesh)
})

//添加底板
let planeGeometry = new THREE.PlaneGeometry(3000, 3000);
let planeMaterial = new THREE.MeshStandardMaterial({ color: 0xcccccc });
// 关闭deptchTest，使该材质无视渲染顺序，必定被渲染（防止重叠闪烁）
planeMaterial.depthTest = false
planeMaterial.depthWrite = true
let plane = new THREE.Mesh(planeGeometry, planeMaterial);
//设置平面需要接收阴影
plane.receiveShadow = true;
scene.add(plane);

if (debug) {
    stat = new Stat()

    //添加到document中
    document.body.append(this.stat.dom)
}


/**
 * 光源设置
 */
// 第二个参数为光照强度，2倍
this.light = new THREE.DirectionalLight(0xFFFAF0, 1)
const { light } = this
light.position.set(600, 600, 600); //点光源位置
light.castShadow = true;//开启阴影
light.shadow.mapSize.width = 4096; //阴影贴图宽度设置为2048像素
light.shadow.mapSize.height = 4096; //阴影贴图高度设置为2048像素
light.shadow.radius = 0;
//Set up shadow properties for the light
light.shadow.camera.near = 100;
light.shadow.camera.far = 3000;
light.shadow.camera.left = -300;
light.shadow.camera.right = 300;
light.shadow.camera.top = 300;
light.shadow.camera.bottom = -300;
// light.shadow.color = '#ff0000'

scene.add(light);
// //环境光 由于环境光作用于所有的物体，所有的材质，所以环境光是没有方向的，也无法产生阴影效果。
scene.add(new THREE.AmbientLight(0xffffff, 0.4));

if (debug) {
    const helper = new THREE.CameraHelper(light.shadow.camera);
    scene.add(helper);
}



/**
 * 相机设置
 */
let width = window.innerWidth; //窗口宽度
let height = window.innerHeight - 150; //窗口高度
var k = width / height; //窗口宽高比
var s = 300; //三维场景显示范围控制系数，系数越大，显示的范围越大
//创建相机对象
const camera = new THREE.PerspectiveCamera(this.fov, width / height, this.near, this.fear);
camera.position.set(400, 0, 500); //设置相机位置
camera.up.x = 0;
camera.up.y = 0;
camera.up.z = 1; //z轴向上
camera.lookAt(scene.position); //设置相机方向(指向的场景对象)

/**
 * 创建渲染器对象
 */
const renderer = new THREE.WebGLRenderer({
    antialias: true, // true/false表示是否开启反锯齿
    alpha: true, // true/false 表示是否可以设置背景色透明
    logarithmicDepthBuffer: true,
    checkShaderErrors: false, //关闭检查提高性能
});
renderer.shadowMap.enabled = true
renderer.shadowMap.needsUpdate = true
renderer.shadowMap.type = THREE.PCFSoftShadowMap
renderer.setSize(width, height);//设置渲染区域尺寸
renderer.setClearColor(0xb9d3ff, 1); //设置背景颜色
renderer.setScissorTest(false)
renderer.setPixelRatio(window.devicePixelRatio);//设置canvas的像素比为当前设备的屏幕像素比，避免高分屏下模糊
renderer.physicallyCorrectLights = false
document.getElementById('app').appendChild(this.renderer.domElement); //body元素中插入canvas对象


const controls = new OrbitControls(camera, renderer.domElement);//创建控件对象
//设置相机角度
//上下翻转的最大角度
controls.maxPolarAngle = 1.4;
//上下翻转的最小角度
controls.minPolarAngle = 0;
//是否允许缩放
controls.enableZoom = true;

controls.enableDamping = true
controls.maxZoom = 10
controls.minZoom = 0.8

//添加标签
//初始化CSS2渲染器
const labelRenderer = new CSS2DRenderer();
labelRenderer.setSize(width, height);
labelRenderer.domElement.style.position = 'absolute';
labelRenderer.domElement.style.pointerEvents = 'none'
labelRenderer.domElement.style.boxSizing = 'border-box'
labelRenderer.domElement.style.top = 0;

document.body.appendChild(this.labelRenderer.domElement);


//render
function render() {
    
    controls.update()
    if (this.stat)
        this.stat.update()

    this.renderer.render(this.scene, this.camera);//执行渲染操作
    this.labelRenderer.render(this.scene, this.camera)

    //指南针

    //只考虑xoy平面，本项目x轴为南，y轴为东，即x轴负方向为正北方向
    //取与相机相反方向的向量，即目光所在的向量
    let dir = new THREE.Vector3(-this.camera.position.x, -this.camera.position.y, 0).normalize();

    let theta = Math.atan2(-dir.y, -dir.x);
    
    //指南针旋转
    $('#guide-wrap .compass').css({ 'transform': 'translate(-50%, -50%) rotate(' + THREE.Math.radToDeg(theta) + 'deg)' });
    requestAnimationFrame(render);
}

render()